<?php
class stYoutubeToolbox_playlist_video_model extends stmodel_2_1{

    public function __construct($config) {
        parent::__construct ( $config );
        $this->setTableName($this->prefix.'st_youtube_playlist_video');
        $this->setPrimaryKey('id');
    }    
        
    public function savestYoutubeToolboxPlaylistVideo($playlistListFeed, $youtube) {
//        $user_id = $playlistListFeed['user_id'];
        $playlistListFeed = $playlistListFeed['playlist_entry'];
        foreach ($playlistListFeed as $playlistEntry) {
            $playlit_id = $playlistEntry->getPlaylistId();
            $feedUrl = $playlistEntry->getPlaylistVideoFeedUrl();
            $playlistVideoFeed = $youtube->getPlaylistVideoFeed($feedUrl);
            foreach ($playlistVideoFeed as $videoEntry) {                
                $data[$i]['id'] = 'NULL';
                $data[$i]['video_id'] = $videoEntry->getVideoId();
                $data[$i]['playlist_id'] = $playlit_id;
                $i++;
            }
           
        }
        if(!empty($data)){
            $this->emptyTable();
            $this->inserRecords($data);
        }        
    }

    public function inserRecords($data = ''){
        if(count($data)>0){
            $query = "INSERT INTO $this->_tableName
                    ( `id`, `video_id`, `playlist_id` )
                    VALUES
                    ";
            $query1 = array();
            foreach ($data as $value) {                
                $query1[] = $this->prepare("(%d, %s, %s)",
                        $value['id'], $value['video_id'], $value['playlist_id']
                        );
            }
            $query1 = implode(', ', $query1);
            $query .= ' '.$query1;
            return $this->query( $query );
        }else{
            return false;
        }
    }

    public function emptyTable(){
        $query = "TRUNCATE TABLE `$this->_tableName`";
        $result = $this->get_var($query);
        return $result;
    }
    

}